const router = require('koa-router')();
const { pool } = require('../config/database');
const { generateToken } = require('../utils/jwt');
const { hashPassword, comparePassword } = require('../utils/password');
const { authMiddleware } = require('../middleware/auth');
const multer = require('@koa/multer');
const path = require('path');
const fs = require('fs');

// 配置头像上传存储目录与文件名
const avatarStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadDir = path.join(__dirname, '..', 'public', 'images', 'avatars');
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    // 使用时间戳+随机数生成文件名，避免依赖 req.user
    const ext = path.extname(file.originalname || '');
    const safeExt = ext || '.png';
    const unique = `${Date.now()}-${Math.round(Math.random() * 1e9)}`;
    cb(null, `${unique}${safeExt}`);
  }
});
const uploadAvatar = multer({ storage: avatarStorage });

router.prefix('/api/users');

// 用户注册
router.post('/register', async (ctx) => {
  try {
    const { username, password, nickname, email, phone } = ctx.request.body;
    
    if (!username || !password) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: '用户名和密码不能为空'
      };
      return;
    }

    // 检查用户名是否已存在
    const [existingUsers] = await pool.execute(
      'SELECT user_id FROM users WHERE username = ?',
      [username]
    );

    if (existingUsers.length > 0) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: '用户名已存在'
      };
      return;
    }

    // 加密密码
    const hashedPassword = await hashPassword(password);

    // 插入新用户
    // 确保所有参数都不是undefined，如果是undefined则转换为null
    const [result] = await pool.execute(
      'INSERT INTO users (username, password, nickname, email, phone) VALUES (?, ?, ?, ?, ?)',
      [username, hashedPassword, nickname || username, email || null, phone || null]
    );

    const token = generateToken({
      userId: result.insertId,
      username: username
    });

    ctx.body = {
      code: 200,
      message: '注册成功',
      data: {
        token,
        user: {
          userId: result.insertId,
          username,
          nickname: nickname || username,
          email,
          phone
        }
      }
    };
  } catch (error) {
    console.error('注册失败:', error);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '服务器内部错误'
    };
  }
});

// 用户登录
router.post('/login', async (ctx) => {
  try {
    const { username, password } = ctx.request.body;
    
    if (!username || !password) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: '用户名和密码不能为空'
      };
      return;
    }

    // 查找用户
    const [users] = await pool.execute(
      'SELECT user_id, username, password, nickname, avatar_url, email, phone FROM users WHERE username = ? AND status = 1',
      [username]
    );

    if (users.length === 0) {
      ctx.status = 401;
      ctx.body = {
        code: 401,
        message: '用户名或密码错误'
      };
      return;
    }

    const user = users[0];

    // 验证密码
    const isPasswordValid = await comparePassword(password, user.password);
    if (!isPasswordValid) {
      ctx.status = 401;
      ctx.body = {
        code: 401,
        message: '用户名或密码错误'
      };
      return;
    }

    // 更新最后登录时间
    await pool.execute(
      'UPDATE users SET last_login_time = NOW() WHERE user_id = ?',
      [user.user_id]
    );

    const token = generateToken({
      userId: user.user_id,
      username: user.username
    });

    ctx.body = {
      code: 200,
      message: '登录成功',
      data: {
        token,
        user: {
          userId: user.user_id,
          username: user.username,
          nickname: user.nickname,
          avatarUrl: user.avatar_url,
          email: user.email,
          phone: user.phone
        }
      }
    };
  } catch (error) {
    console.error('登录失败:', error);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '服务器内部错误'
    };
  }
});

// 获取用户信息
router.get('/profile', authMiddleware, async (ctx) => {
  try {
    const userId = ctx.user.userId;

    const [users] = await pool.execute(
      'SELECT user_id, username, nickname, avatar_url, email, phone, register_time, last_login_time FROM users WHERE user_id = ?',
      [userId]
    );

    if (users.length === 0) {
      ctx.status = 404;
      ctx.body = {
        code: 404,
        message: '用户不存在'
      };
      return;
    }

    ctx.body = {
      code: 200,
      message: '获取用户信息成功',
      data: users[0]
    };
  } catch (error) {
    console.error('获取用户信息失败:', error);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '服务器内部错误'
    };
  }
});

// 更新用户信息
router.put('/profile', authMiddleware, async (ctx) => {
  try {
    const userId = ctx.user.userId;
    const { nickname, avatar_url, email, phone } = ctx.request.body;

    await pool.execute(
      'UPDATE users SET nickname = ?, avatar_url = ?, email = ?, phone = ? WHERE user_id = ?',
      [nickname, avatar_url, email, phone, userId]
    );

    ctx.body = {
      code: 200,
      message: '更新用户信息成功'
    };
  } catch (error) {
    console.error('更新用户信息失败:', error);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '服务器内部错误'
    };
  }
});

/**
 * 上传并更新用户头像
 * form-data:
 *  - file: 头像文件
 */
router.post('/avatar', authMiddleware, uploadAvatar.single('file'), async (ctx) => {
  try {
    const userId = ctx.user.userId;
    const file = ctx.file;

    if (!file) {
      ctx.status = 400;
      ctx.body = { code: 400, message: '未接收到头像文件' };
      return;
    }

    // 生成对外可访问的URL
    const relativePath = `/images/avatars/${file.filename}`;
    const publicUrl = `${ctx.origin}${relativePath}`;

    // 更新数据库头像地址
    await pool.execute(
      'UPDATE users SET avatar_url = ? WHERE user_id = ?',
      [publicUrl, userId]
    );

    ctx.body = {
      code: 200,
      message: '头像更新成功',
      data: { avatarUrl: publicUrl }
    };
  } catch (error) {
    console.error('头像上传失败:', error);
    ctx.status = 500;
    ctx.body = { code: 500, message: '服务器内部错误' };
  }
});

module.exports = router;
